﻿using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

namespace Framework
{
    public class LocalResLoader : ResLoader
    {
        private AsyncOperationHandle<Object> _handle;
        
        public LocalResLoader(Resource resource) : base(resource)
        {
        }

        protected override void OnStart()
        {
            _handle = Addressables.LoadAssetAsync<Object>(resource.url);
            _handle.Completed += OnAssetLoaded;
        }

        protected override void OnCancel()
        {
            _handle.Completed -= OnAssetLoaded;
            Addressables.Release(_handle);
            _handle = default;
        }

        private void OnAssetLoaded(AsyncOperationHandle<Object> handle)
        {
            _handle.Completed -= OnAssetLoaded;
            resource.SetHandle(handle);
        }
    }
}